#include "UdpServer.hpp"
#include "Log.hpp"
#include <memory>
#include <vector>

Log lg;

void Usage(std::string proc) // 实现动态调整端口号
{
    std::cout << "\n\rUsage: " << proc << " port[1024+]\n"
              << std::endl;
}

std::string Handler(const std::string &info,const std::string &clientip,uint16_t clientport)
{
    std::cout<<"["<<clientip<<":"<<clientport<<"]#"<<info<<std::endl;
    std::string res = "Server get a message: ";
    res += info;
    std::cout << res << std::endl;

    // pid_t id = fork();
    // if(id == 0)
    // {
    //     // ls -a -l -> "ls" "-a" "-l"
    //     // exec*();
    // }
    return res;
}

bool SafeCheck(const std::string &cmd) // 安全检查
{
    int safe = false;
    std::vector<std::string> key_word = {
        "rm",
        "mv",
        "cp",
        "kill",
        "sudo",
        "unlink",
        "uninstall",
        "yum",
        "top",
        "while"};
    for (auto &word : key_word)
    {
        auto pos = cmd.find(word); // 包含任意一个非法子串就返回false
        if (pos != std::string::npos)
            return false;
    }
    return true;
}

std::string ExcuteCommand(const std::string &cmd)
{
    std::cout << "get a requst cmd: " << cmd << std::endl;
    if (!SafeCheck(cmd))
        return "Bad man";

    FILE *fp = popen(cmd.c_str(), "r");
    if (nullptr == fp)
    {
        perror("popen");
        return "error";
    }
    std::string result;
    char buffer[4096];
    while (true)
    {
        char *ok = fgets(buffer, sizeof(buffer), fp);
        if (ok == nullptr)
            break;
        result += buffer;
    }
    pclose(fp);

    return result;
}

// ./udpserver port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }

    uint16_t port = std::stoi(argv[1]);

    std::unique_ptr<UdpServer> svr(new UdpServer(port)); // 构建一个Udp服务器

    // std::unique_ptr<UdpServer> svr(new UdpServer(8080,"47.120.39.156"));  //构建一个Udp服务器
    //  bind error, error: 99,err string: Cannot assign requested address
    //  这里保存，因为云服务器禁止bind公网ip

    // 将来发到我的机器上的的地址，忽略ip地址直接看报文
    // std::unique_ptr<UdpServer> svr(new UdpServer(8080));

    svr->Init();             // 初始化服务器
    //svr->Run(ExcuteCommand); // 运行服务器
    //svr->Run(Handler); // 运行服务器
    svr->Run();
    return 0;
}